package com.ctshk.rpc.custom.service.impl;
import java.math.BigDecimal;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.GlobalConstants;
import com.ctshk.common.enums.NumberConstant;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.Currency;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.req.MainData;
import com.ctshk.common.utils.DateUtil;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.custom.dto.quotation.*;
import com.ctshk.rpc.custom.entity.*;
import com.ctshk.rpc.custom.json.ContactTelephoneJson;
import com.ctshk.rpc.custom.mapper.*;
import com.ctshk.rpc.custom.req.ContactReq;
import com.ctshk.rpc.custom.req.CustomerTypeReq;
import com.ctshk.rpc.custom.req.QuotationTouristTypeReq;
import com.ctshk.rpc.custom.req.quotation.*;
import com.ctshk.rpc.custom.service.ICustomizedQuotationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.rpc.system.dto.SysDepartmentDTO;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.service.ISysDepartmentService;
import com.ctshk.rpc.system.service.ISysPermissionService;
import com.ctshk.rpc.system.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 报价单 服务实现类
 * </p>
 *
 * @author 谢诗宏
 * @since 2021-01-16
 */
@DubboService
public class CustomizedQuotationServiceImpl extends ServiceImpl<CustomizedQuotationMapper, CustomizedQuotation> implements ICustomizedQuotationService {

    @Autowired
    private CustomizedInquiryMapper customizedInquiryMapper;

    @DubboReference
    private ISysUserService sysUserService;

    @Autowired
    private CustomizedQuotationMapper quotationMapper;
    @Autowired
    private CustomizedQuotationFreeQuotePackageMapper freeQuotePackageMapper;
    @Autowired
    private CustomizedQuotationFreeQuoteServiceItemsMapper freeQuoteServiceItemsMapper;
    @Autowired
    private CustomizedQuotationTouristTypeMapper quotationTouristTypeMapper;
    @Autowired
    private CustomizedQuotationTouristPriceMapper quotationTouristPriceMapper;
    @Autowired
    private CustomizedQuotationTripQuoteMapper quotationTripQuoteMapper;
    @Autowired
    private CustomizedQuotationTripQuoteServiceItemsMapper quotationTripQuoteServiceItemsMapper;
    @Autowired
    private CustomizedQuotationCollectionFeeMapper quotationCollectionFeeMapper;
    @Autowired
    private CustomizedQuotationCollectionTouristFeeMapper quotationCollectionTouristFeeMapper;

    @DubboReference
    private ISysDepartmentService sysDepartmentService;
    @DubboReference
    private ISysPermissionService sysPermissionService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public long add(QuotationReq quotationReq, long userId) {
        if (quotationReq.getDepartType() == null){
            quotationReq.setDepartType(3);
        }
        CustomizedQuotation customizedQuotation = new CustomizedQuotation();
        Long quotationId = SnowflakeIdWorker.nextId();
        SysDepartmentDTO sysDepartmentDTO = sysDepartmentService.queryByUserId(userId);
        // 报价单号 生成规则：BJ+報價人員部門代碼+年份(2位)+月份+日期+四位隨機字符
        String quotationNumber = "BJ" + sysDepartmentDTO.getDeptCode() + DateUtil.fmtNum(LocalDate.now()) + RandomUtil.randomNumbers(4);
        customizedQuotation.setId(quotationId);
        customizedQuotation.setQuotationNumber(quotationNumber);
        customizedQuotation.setDepartType(quotationReq.getDepartType());
        Integer customerType;
        String inquiryNumber = null;
        Long bigClientId;
        String bigClientName;
        String contactCnSurname;
        String contactCnName;
        String contactEnSurname;
        String contactEnName;
        Long contactGender;
        Long contactTelAreaCode;
        String contactTelephones;
        String contactEmail;
        String internalRemark;
        if (quotationReq.getInquiryId() != null) {
            // 询价单报价客户信息
            CustomizedInquiry customizedInquiry = customizedInquiryMapper.selectById(quotationReq.getInquiryId());
            if (customizedInquiry == null || customizedInquiry.getIsDeleted() == 1) {
                throw new BusinessException(SystemError.CUSTOM_3000);
            }
            customizedQuotation.setInquiryId(customizedInquiry.getId());

            // 设置询价单状态为已报价
            customizedInquiry.setInquiryStatus(7);
            //填充报价单信息
            customizedInquiry.setQuotationId(quotationId);
            customizedInquiry.setQuotationNumber(quotationNumber);
            customizedInquiryMapper.updateById(customizedInquiry);

            inquiryNumber = customizedInquiry.getInquiryNumber();
            customerType = customizedInquiry.getCustomerType();
            bigClientId = customizedInquiry.getBigClientId();
            bigClientName = customizedInquiry.getBigClientName();
            contactCnSurname = customizedInquiry.getContactCnSurname();
            contactCnName = customizedInquiry.getContactCnName();
            contactEnSurname = customizedInquiry.getContactEnSurname();
            contactEnName = customizedInquiry.getContactEnName();
            contactGender = customizedInquiry.getContactGender();
            contactTelephones = customizedInquiry.getContactTelephones();
            contactEmail = customizedInquiry.getContactEmail();
            internalRemark = customizedInquiry.getInternalRemark();
        } else {
            // 无询价单报价-客户信息
            customerType = quotationReq.getCustomerTypeReq().getCustomerType();
            bigClientId = quotationReq.getCustomerTypeReq().getBigClientId();
            bigClientName = quotationReq.getCustomerTypeReq().getBigClientName();
            contactCnSurname = quotationReq.getContactReq().getContactCnSurname();
            contactCnName = quotationReq.getContactReq().getContactCnName();
            contactEnSurname = quotationReq.getContactReq().getContactEnSurname();
            contactEnName = quotationReq.getContactReq().getContactEnName();
            contactGender = quotationReq.getContactGender();
            contactEmail = quotationReq.getContactEmail();
            internalRemark = quotationReq.getInternalRemark();

            JSONObject contactTel = new JSONObject();
            contactTel.put("areaCode", quotationReq.getContactTelAreaCode());
            contactTel.put("phones", quotationReq.getContactTelephones());
            contactTelephones = contactTel.toJSONString();
        }
        /**
         * 询价单相关
         */
        customizedQuotation.setInquiryNumber(inquiryNumber);
        customizedQuotation.setCustomerType(customerType);
        customizedQuotation.setBigClientId(bigClientId);
        customizedQuotation.setBigClientName(bigClientName);
        customizedQuotation.setContactCnSurname(contactCnSurname);
        customizedQuotation.setContactCnName(contactCnName);
        customizedQuotation.setContactEnSurname(contactEnSurname);
        customizedQuotation.setContactEnName(contactEnName);
        customizedQuotation.setContactGender(contactGender);
        customizedQuotation.setContactTelephones(contactTelephones);
        customizedQuotation.setContactEmail(contactEmail);
        customizedQuotation.setInternalRemark(internalRemark);

        customizedQuotation.setQuotationTitle(quotationReq.getQuotationTitle());
        customizedQuotation.setInstruction(quotationReq.getInstruction());
        customizedQuotation.setQuotationType(quotationReq.getQuotationType());
        customizedQuotation.setGroupFeeType(quotationReq.getGroupFeeType());
        // customizedQuotation.setBeginDate();
        // customizedQuotation.setEndDate();
        customizedQuotation.setQuotationStatus(2);
        customizedQuotation.setCreateId(userId);

        quotationMapper.insert(customizedQuotation);

        /**
         * 自由报价
         */
        if (quotationReq.getQuotationType() == 1) {
            Optional.ofNullable(quotationReq.getReqPackages()).orElse(new ArrayList<>()).forEach(freeQuoteReqPackage -> {
                // 自由报价主套餐数据
                CustomizedQuotationFreeQuotePackage freeQuotePackage = new CustomizedQuotationFreeQuotePackage();
                Long packageId = SnowflakeIdWorker.nextId();
                freeQuotePackage.setId(packageId);
                freeQuotePackage.setQuotationId(quotationId);
                freeQuotePackage.setName(freeQuoteReqPackage.getPackageName());
                freeQuotePackage.setTotalPeople(freeQuoteReqPackage.getTotalPeople());
                freeQuotePackage.setTotalAmount(freeQuoteReqPackage.getTotalAmount());
                freeQuotePackage.setCurrencyId(freeQuoteReqPackage.getCurrency().getValue());
                freeQuotePackage.setCurrency(freeQuoteReqPackage.getCurrency().getText());
                freeQuotePackage.setExchangeRate(freeQuoteReqPackage.getCurrency().getMarketExchangeRate());
                freeQuotePackage.setCreateId(userId);
                freeQuotePackageMapper.insert(freeQuotePackage);
                // 套餐内旅客类型数据,长者人数成人人数小童人数等
                List<QuotationTouristTypeReq> packageTouristTypes = freeQuoteReqPackage.getPackageTouristTypes();
                Optional.ofNullable(packageTouristTypes).orElse(new ArrayList<>()).forEach(quotationTouristTypeReq -> {
                    CustomizedQuotationTouristType quotationTouristType = new CustomizedQuotationTouristType();
                    quotationTouristType.setId(SnowflakeIdWorker.nextId());
                    quotationTouristType.setInquiryId(quotationReq.getInquiryId());
                    quotationTouristType.setQuotationId(quotationId);
                    quotationTouristType.setPackageId(packageId);
                    quotationTouristType.setMainDataId(quotationTouristTypeReq.getValue());
                    quotationTouristType.setName(quotationTouristTypeReq.getLabel());
                    quotationTouristType.setPeopleNum(quotationTouristTypeReq.getPeopleNum());
                    quotationTouristType.setAgeBegin(quotationTouristTypeReq.getAgeBegin());
                    quotationTouristType.setAgeEnd(quotationTouristTypeReq.getAgeEnd());
                    quotationTouristType.setCreateId(userId);
                    quotationTouristTypeMapper.insert(quotationTouristType);
                });
                // 套餐内服务项目数据,住宿车票门票等
                List<FreeQuoteServiceItemsReq> serviceItemsReqs = freeQuoteReqPackage.getServiceItemsReqs();
                Optional.ofNullable(serviceItemsReqs).orElse(new ArrayList<>()).forEach(quoteServiceItemsReq -> {
                    CustomizedQuotationFreeQuoteServiceItems quoteServiceItems = new CustomizedQuotationFreeQuoteServiceItems();
                    Long serviceItemId = SnowflakeIdWorker.nextId();
                    quoteServiceItems.setId(serviceItemId);
                    quoteServiceItems.setPackageId(packageId);
                    quoteServiceItems.setQuotationId(quotationId);
                    // 团费类型冗余
                    quoteServiceItems.setGroupFeeType(quotationReq.getGroupFeeType());
                    quoteServiceItems.setMainDataId(quoteServiceItemsReq.getServiceType().getValue());
                    quoteServiceItems.setServiceTypeName(quoteServiceItemsReq.getServiceType().getLabel());
                    quoteServiceItems.setName(quoteServiceItemsReq.getProjectName());
                    quoteServiceItems.setServiceInstruction(quoteServiceItemsReq.getServiceInstruction());
                    quoteServiceItems.setSinglePrice(quoteServiceItemsReq.getSinglePrice());
                    quoteServiceItems.setTotalNum(quoteServiceItemsReq.getTotalNum());
                    quoteServiceItems.setTotalPrice(quoteServiceItemsReq.getTotalPrice());
                    quoteServiceItems.setCreateId(userId);
                    freeQuoteServiceItemsMapper.insert(quoteServiceItems);
                    // 服务项目里的动态旅客类型价格,长者价格成人价格小童价格等
                    List<TouristPriceReq> touristPriceReqs = quoteServiceItemsReq.getTouristPriceReqs();
                    Optional.ofNullable(touristPriceReqs).orElse(new ArrayList<>()).forEach(touristPriceReq -> {
                        CustomizedQuotationTouristPrice quotationTouristPrice = new CustomizedQuotationTouristPrice();
                        quotationTouristPrice.setId(SnowflakeIdWorker.nextId());
                        quotationTouristPrice.setTouristTypeName(touristPriceReq.getTouristTypeName());
                        quotationTouristPrice.setTouristTypeId(touristPriceReq.getTouristTypeId());
                        quotationTouristPrice.setServiceItemId(serviceItemId);
                        quotationTouristPrice.setPackageId(packageId);
                        quotationTouristPrice.setQuotationId(quotationId);
                        if (touristPriceReq.getPrice() == null){
                            quotationTouristPrice.setTotalPrice(BigDecimal.ZERO);
                        }else{
                            quotationTouristPrice.setTotalPrice(touristPriceReq.getPrice());
                        }
                        quotationTouristPrice.setCreateId(userId);
                        quotationTouristPriceMapper.insert(quotationTouristPrice);
                    });
                });
            });
        } else {
            /**
             * 行程报价
             */

            // 获取行程报价的旅客人数
            List<QuotationTouristTypeReq> touristTypes = quotationReq.getTouristTypes();
            Optional.ofNullable(touristTypes).orElse(new ArrayList<>()).forEach(touristTypeReq -> {
                CustomizedQuotationTouristType quotationTouristType = new CustomizedQuotationTouristType();
                quotationTouristType.setId(SnowflakeIdWorker.nextId());
                quotationTouristType.setInquiryId(quotationReq.getInquiryId());
                quotationTouristType.setQuotationId(quotationId);
                quotationTouristType.setMainDataId(touristTypeReq.getValue());
                quotationTouristType.setName(touristTypeReq.getLabel());
                quotationTouristType.setPeopleNum(touristTypeReq.getPeopleNum());
                quotationTouristType.setAgeBegin(touristTypeReq.getAgeBegin());
                quotationTouristType.setAgeEnd(touristTypeReq.getAgeEnd());
                quotationTouristType.setCreateId(userId);
                quotationTouristTypeMapper.insert(quotationTouristType);
            });
            // 获取天数行程数组
            List<TripQuoteReq> tripQuoteReqs = quotationReq.getTripQuoteReqs();
            for (int i = 0; i < tripQuoteReqs.size(); i++) {
                // 遍历新增行程天数
                CustomizedQuotationTripQuote quotationTripQuote = new CustomizedQuotationTripQuote();
                Long tripQuoteId = SnowflakeIdWorker.nextId();
                quotationTripQuote.setId(tripQuoteId);
                quotationTripQuote.setQuotationId(quotationId);
                quotationTripQuote.setTotalPeople(0);
                quotationTripQuote.setTotalAmount(tripQuoteReqs.get(i).getTotalAmount());
                quotationTripQuote.setDay(i);
                quotationTripQuote.setCurrencyId(tripQuoteReqs.get(i).getCurrency().getValue());
                quotationTripQuote.setCurrency(tripQuoteReqs.get(i).getCurrency().getText());
                quotationTripQuote.setExchangeRate(tripQuoteReqs.get(i).getCurrency().getMarketExchangeRate());
                quotationTripQuote.setCreateId(userId);
                quotationTripQuoteMapper.insert(quotationTripQuote);

                // 遍历新增单个行程天数内的服务项目
                List<TripQuoteServiceItemsReq> serviceItems = tripQuoteReqs.get(i).getServiceItems();
                Optional.ofNullable(serviceItems).orElse(new ArrayList<>()).forEach(tripQuoteServiceItemsReq -> {
                    CustomizedQuotationTripQuoteServiceItems quoteServiceItems = new CustomizedQuotationTripQuoteServiceItems();
                    quoteServiceItems.setId(SnowflakeIdWorker.nextId());
                    quoteServiceItems.setQuotationId(quotationId);
                    quoteServiceItems.setDateId(tripQuoteId);
                    quoteServiceItems.setMainDataId(tripQuoteServiceItemsReq.getServiceType().getValue());
                    quoteServiceItems.setServiceTypeName(tripQuoteServiceItemsReq.getServiceType().getLabel());
                    quoteServiceItems.setName(tripQuoteServiceItemsReq.getProjectName());
                    quoteServiceItems.setServiceInstruction(tripQuoteServiceItemsReq.getServiceInstruction());
                    quoteServiceItems.setSinglePrice(tripQuoteServiceItemsReq.getSinglePrice());
                    quoteServiceItems.setTotalNum(tripQuoteServiceItemsReq.getAmount());
                    quoteServiceItems.setTotalPrice(tripQuoteServiceItemsReq.getTotalPrice());
                    quoteServiceItems.setCreateId(userId);
                    quotationTripQuoteServiceItemsMapper.insert(quoteServiceItems);
                });
            }
        }

        /**
         * 代收费用
         */
        List<CollectionFeeReq> collectionFees = quotationReq.getCollectionFees();
        Optional.ofNullable(collectionFees).orElse(new ArrayList<>()).forEach(collectionFeeReq -> {
            // 遍历新增代收费用
            CustomizedQuotationCollectionFee quotationCollectionFee = new CustomizedQuotationCollectionFee();
            Long collectionId = SnowflakeIdWorker.nextId();
            quotationCollectionFee.setId(collectionId);
            quotationCollectionFee.setQuotationId(quotationId);
            // TODO 代收费用类型临时注释
            if (collectionFeeReq.getProject() != null){
                quotationCollectionFee.setMainDataId(collectionFeeReq.getProject().getValue());
                quotationCollectionFee.setProjectName(collectionFeeReq.getProject().getLabel());
            }
            quotationCollectionFee.setCurrencyId(collectionFeeReq.getCurrency().getValue());
            quotationCollectionFee.setCurrency(collectionFeeReq.getCurrency().getText());
            quotationCollectionFee.setExchangeRate(collectionFeeReq.getCurrency().getMarketExchangeRate());
            quotationCollectionFee.setRemark(collectionFeeReq.getRemark());
            quotationCollectionFee.setCreateId(userId);
            quotationCollectionFeeMapper.insert(quotationCollectionFee);
            // 代收费用服务项目
            List<CollectionTouristFeeReq> touristFees = collectionFeeReq.getTouristFees();
            Optional.ofNullable(touristFees).orElse(new ArrayList<>()).forEach(collectionTouristFeeReq -> {
                CustomizedQuotationCollectionTouristFee quotationCollectionTouristFee = new CustomizedQuotationCollectionTouristFee();
                quotationCollectionTouristFee.setId(SnowflakeIdWorker.nextId());
                quotationCollectionTouristFee.setQuotationId(quotationId);
                quotationCollectionTouristFee.setCollectionId(collectionId);
                quotationCollectionTouristFee.setTouristTypeId(collectionTouristFeeReq.getTouristTypeId());
                quotationCollectionTouristFee.setTouristTypeName(collectionTouristFeeReq.getTouristTypeName());
                quotationCollectionTouristFee.setTotalAmount(collectionTouristFeeReq.getAmount());
                quotationCollectionTouristFee.setCurrencyId(collectionTouristFeeReq.getCurrencyId());
                quotationCollectionTouristFee.setCurrency(collectionTouristFeeReq.getCurrencyName());
                quotationCollectionTouristFee.setExchangeRate(collectionTouristFeeReq.getExchangeRate());
                quotationCollectionTouristFeeMapper.insert(quotationCollectionTouristFee);
            });
        });
        return quotationId;
    }


    /**
     * 编辑报价单
     *
     * @param quotationReq
     * @param userId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public long put(QuotationReq quotationReq, long userId) {
        CustomizedQuotation customizedQuotation = new CustomizedQuotation();
        Long quotationId = quotationReq.getId();
        customizedQuotation.setId(quotationId);

        Integer customerType;
        String inquiryNumber = null;
        Long bigClientId;
        String bigClientName;
        String contactCnSurname;
        String contactCnName;
        String contactEnSurname;
        String contactEnName;
        Long contactGender;
        Long contactTelAreaCode;
        String contactTelephones;
        String contactEmail;
        String internalRemark;
        if (null != quotationReq.getInquiryId()) {
            // 询价单报价客户信息
            CustomizedInquiry customizedInquiry = customizedInquiryMapper.selectById(quotationReq.getInquiryId());
            if (null == customizedInquiry || customizedInquiry.getIsDeleted() == 1) {
                throw new BusinessException(SystemError.CUSTOM_3000);
            }
            customizedQuotation.setInquiryId(customizedInquiry.getId());

            // 设置询价单状态为已报价
            customizedInquiry.setInquiryStatus(7);
            customizedInquiryMapper.updateById(customizedInquiry);

            inquiryNumber = customizedInquiry.getInquiryNumber();
            customerType = customizedInquiry.getCustomerType();
            bigClientId = customizedInquiry.getBigClientId();
            bigClientName = customizedInquiry.getBigClientName();
            contactCnSurname = customizedInquiry.getContactCnSurname();
            contactCnName = customizedInquiry.getContactCnName();
            contactEnSurname = customizedInquiry.getContactEnSurname();
            contactEnName = customizedInquiry.getContactEnName();
            contactGender = customizedInquiry.getContactGender();
            contactTelephones = customizedInquiry.getContactTelephones();
            contactEmail = customizedInquiry.getContactEmail();
            internalRemark = customizedInquiry.getInternalRemark();
        } else {
            // 无询价单报价-客户信息
            customerType = quotationReq.getCustomerTypeReq().getCustomerType();
            bigClientId = quotationReq.getCustomerTypeReq().getBigClientId();
            bigClientName = quotationReq.getCustomerTypeReq().getBigClientName();
            contactCnSurname = quotationReq.getContactReq().getContactCnSurname();
            contactCnName = quotationReq.getContactReq().getContactCnName();
            contactEnSurname = quotationReq.getContactReq().getContactEnSurname();
            contactEnName = quotationReq.getContactReq().getContactEnName();
            contactGender = quotationReq.getContactGender();
            contactEmail = quotationReq.getContactEmail();
            internalRemark = quotationReq.getInternalRemark();

            JSONObject contactTel = new JSONObject();
            contactTel.put("areaCode", quotationReq.getContactTelAreaCode());
            contactTel.put("phones", quotationReq.getContactTelephones());
            contactTelephones = contactTel.toJSONString();
        }
        /**
         * 询价单相关
         */
        customizedQuotation.setInquiryNumber(inquiryNumber);
        customizedQuotation.setCustomerType(customerType);
        customizedQuotation.setBigClientId(bigClientId);
        customizedQuotation.setBigClientName(bigClientName);
        customizedQuotation.setContactCnSurname(contactCnSurname);
        customizedQuotation.setContactCnName(contactCnName);
        customizedQuotation.setContactEnSurname(contactEnSurname);
        customizedQuotation.setContactEnName(contactEnName);
        customizedQuotation.setContactGender(contactGender);
        customizedQuotation.setContactTelephones(contactTelephones);
        customizedQuotation.setContactEmail(contactEmail);
        customizedQuotation.setInternalRemark(internalRemark);

        customizedQuotation.setQuotationTitle(quotationReq.getQuotationTitle());
        customizedQuotation.setInstruction(quotationReq.getInstruction());
        customizedQuotation.setQuotationType(quotationReq.getQuotationType());
        customizedQuotation.setGroupFeeType(quotationReq.getGroupFeeType());
        // customizedQuotation.setBeginDate();
        // customizedQuotation.setEndDate();
        customizedQuotation.setQuotationStatus(2);
        customizedQuotation.setCreateId(userId);
        // 更新报价表记录
        quotationMapper.updateById(customizedQuotation);

        /**
         * 自由报价
         */
        if (1 == quotationReq.getQuotationType()) {
            // 编辑报价时需删除关联表再更新
            QueryWrapper<CustomizedQuotationFreeQuotePackage> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("quotation_id",quotationId);
            CustomizedQuotationFreeQuotePackage customizedQuotationFreeQuotePackage = new CustomizedQuotationFreeQuotePackage();
            customizedQuotationFreeQuotePackage.setIsDeleted(1);
            customizedQuotationFreeQuotePackage.setModifiedId(userId);
            freeQuotePackageMapper.update(customizedQuotationFreeQuotePackage,queryWrapper);

            QueryWrapper<CustomizedQuotationTouristType> typeQueryWrapper = new QueryWrapper<>();
            typeQueryWrapper.eq("quotation_id",quotationId);
            CustomizedQuotationTouristType customizedQuotationTouristType = new CustomizedQuotationTouristType();
            customizedQuotationTouristType.setIsDeleted(1);
            customizedQuotationTouristType.setModifiedId(userId);
            quotationTouristTypeMapper.update(customizedQuotationTouristType,typeQueryWrapper);

            QueryWrapper<CustomizedQuotationFreeQuoteServiceItems> itemsQueryWrapper = new QueryWrapper<>();
            itemsQueryWrapper.eq("quotation_id",quotationId);
            CustomizedQuotationFreeQuoteServiceItems quoteServiceItem = new CustomizedQuotationFreeQuoteServiceItems();
            quoteServiceItem.setIsDeleted(1);
            quoteServiceItem.setModifiedId(userId);
            freeQuoteServiceItemsMapper.update(quoteServiceItem,itemsQueryWrapper);
            // 游客服务价格表数据直接硬删除
            QueryWrapper<CustomizedQuotationTouristPrice> priceQueryWrapper = new QueryWrapper<>();
            priceQueryWrapper.eq("quotation_id",quotationId);
            List<CustomizedQuotationTouristPrice> touristPriceList = quotationTouristPriceMapper.selectList(priceQueryWrapper);
            if(CollectionUtils.isNotEmpty(touristPriceList)){
                List<Long> ids = touristPriceList.stream().map(CustomizedQuotationTouristPrice::getId).distinct().collect(Collectors.toList());
                quotationTouristPriceMapper.deleteBatchIds(ids);
            }

            Optional.ofNullable(quotationReq.getReqPackages()).orElse(new ArrayList<>()).forEach(freeQuoteReqPackage -> {
                // 自由报价主套餐数据
                CustomizedQuotationFreeQuotePackage freeQuotePackage = new CustomizedQuotationFreeQuotePackage();
                Long packageId = SnowflakeIdWorker.nextId();
                freeQuotePackage.setId(packageId);
                freeQuotePackage.setQuotationId(quotationId);
                freeQuotePackage.setName(freeQuoteReqPackage.getPackageName());
                freeQuotePackage.setTotalPeople(freeQuoteReqPackage.getTotalPeople());
                freeQuotePackage.setTotalAmount(freeQuoteReqPackage.getTotalAmount());
                freeQuotePackage.setCurrencyId(freeQuoteReqPackage.getCurrency().getValue());
                freeQuotePackage.setCurrency(freeQuoteReqPackage.getCurrency().getText());
                freeQuotePackage.setExchangeRate(freeQuoteReqPackage.getCurrency().getMarketExchangeRate());
                freeQuotePackage.setCreateId(userId);
                freeQuotePackageMapper.insert(freeQuotePackage);
                // 套餐内旅客类型数据,长者人数成人人数小童人数等
                List<QuotationTouristTypeReq> packageTouristTypes = freeQuoteReqPackage.getPackageTouristTypes();
                Optional.ofNullable(packageTouristTypes).orElse(new ArrayList<>()).forEach(quotationTouristTypeReq -> {
                    CustomizedQuotationTouristType quotationTouristType = new CustomizedQuotationTouristType();
                    quotationTouristType.setId(SnowflakeIdWorker.nextId());
                    quotationTouristType.setInquiryId(quotationReq.getInquiryId());
                    quotationTouristType.setQuotationId(quotationId);
                    quotationTouristType.setPackageId(packageId);
                    quotationTouristType.setMainDataId(quotationTouristTypeReq.getValue());
                    quotationTouristType.setName(quotationTouristTypeReq.getLabel());
                    quotationTouristType.setPeopleNum(quotationTouristTypeReq.getPeopleNum());
                    quotationTouristType.setAgeBegin(quotationTouristTypeReq.getAgeBegin());
                    quotationTouristType.setAgeEnd(quotationTouristTypeReq.getAgeEnd());
                    quotationTouristType.setCreateId(userId);
                    quotationTouristTypeMapper.insert(quotationTouristType);
                });
                // 套餐内服务项目数据,住宿车票门票等
                List<FreeQuoteServiceItemsReq> serviceItemsReqs = freeQuoteReqPackage.getServiceItemsReqs();
                Optional.ofNullable(serviceItemsReqs).orElse(new ArrayList<>()).forEach(quoteServiceItemsReq -> {
                    CustomizedQuotationFreeQuoteServiceItems quoteServiceItems = new CustomizedQuotationFreeQuoteServiceItems();
                    Long serviceItemId = SnowflakeIdWorker.nextId();
                    quoteServiceItems.setId(serviceItemId);
                    quoteServiceItems.setPackageId(packageId);
                    quoteServiceItems.setQuotationId(quotationId);
                    // 团费类型冗余
                    quoteServiceItems.setGroupFeeType(quotationReq.getGroupFeeType());
                    quoteServiceItems.setMainDataId(quoteServiceItemsReq.getServiceType().getValue());
                    quoteServiceItems.setServiceTypeName(quoteServiceItemsReq.getServiceType().getLabel());
                    quoteServiceItems.setName(quoteServiceItemsReq.getProjectName());
                    quoteServiceItems.setServiceInstruction(quoteServiceItemsReq.getServiceInstruction());
                    quoteServiceItems.setSinglePrice(quoteServiceItemsReq.getSinglePrice());
                    quoteServiceItems.setTotalNum(quoteServiceItemsReq.getTotalNum());
                    quoteServiceItems.setTotalPrice(quoteServiceItemsReq.getTotalPrice());
                    quoteServiceItems.setCreateId(userId);
                    freeQuoteServiceItemsMapper.insert(quoteServiceItems);
                    // 服务项目里的动态旅客类型价格,长者价格成人价格小童价格等
                    List<TouristPriceReq> touristPriceReqs = quoteServiceItemsReq.getTouristPriceReqs();
                    Optional.ofNullable(touristPriceReqs).orElse(new ArrayList<>()).forEach(touristPriceReq -> {
                        CustomizedQuotationTouristPrice quotationTouristPrice = new CustomizedQuotationTouristPrice();
                        quotationTouristPrice.setId(SnowflakeIdWorker.nextId());
                        quotationTouristPrice.setTouristTypeName(touristPriceReq.getTouristTypeName());
                        quotationTouristPrice.setTouristTypeId(touristPriceReq.getTouristTypeId());
                        quotationTouristPrice.setServiceItemId(serviceItemId);
                        quotationTouristPrice.setPackageId(packageId);
                        quotationTouristPrice.setQuotationId(quotationId);
                        if (touristPriceReq.getPrice() == null){
                            quotationTouristPrice.setTotalPrice(BigDecimal.ZERO);
                        }else{
                            quotationTouristPrice.setTotalPrice(touristPriceReq.getPrice());
                        }
                        quotationTouristPrice.setCreateId(userId);
                        quotationTouristPriceMapper.insert(quotationTouristPrice);
                    });
                });
            });
        } else {
            /**
             * 行程报价
             */
            QueryWrapper<CustomizedQuotationTouristType> typeQueryWrapper = new QueryWrapper<>();
            typeQueryWrapper.eq("quotation_id",quotationId);
            CustomizedQuotationTouristType customizedQuotationTouristType = new CustomizedQuotationTouristType();
            customizedQuotationTouristType.setIsDeleted(1);
            customizedQuotationTouristType.setModifiedId(userId);
            quotationTouristTypeMapper.update(customizedQuotationTouristType,typeQueryWrapper);

            QueryWrapper<CustomizedQuotationTripQuote> tripQuoteQueryWrapper = new QueryWrapper<>();
            tripQuoteQueryWrapper.eq("quotation_id",quotationId);
            CustomizedQuotationTripQuote quote = new CustomizedQuotationTripQuote();
            quote.setIsDeleted(1);
            quote.setModifiedId(userId);
            quotationTripQuoteMapper.update(quote,tripQuoteQueryWrapper);

            QueryWrapper<CustomizedQuotationTripQuoteServiceItems> itemsQueryWrapper = new QueryWrapper<>();
            itemsQueryWrapper.eq("quotation_id",quotationId);
            CustomizedQuotationTripQuoteServiceItems quoteItems = new CustomizedQuotationTripQuoteServiceItems();
            quoteItems.setIsDeleted(1);
            quoteItems.setModifiedId(userId);
            quotationTripQuoteServiceItemsMapper.update(quoteItems,itemsQueryWrapper);

            // 获取行程报价的旅客人数
            List<QuotationTouristTypeReq> touristTypes = quotationReq.getTouristTypes();
            Optional.ofNullable(touristTypes).orElse(new ArrayList<>()).forEach(touristTypeReq -> {
                CustomizedQuotationTouristType quotationTouristType = new CustomizedQuotationTouristType();
                quotationTouristType.setId(SnowflakeIdWorker.nextId());
                quotationTouristType.setInquiryId(quotationReq.getInquiryId());
                quotationTouristType.setQuotationId(quotationId);
                quotationTouristType.setMainDataId(touristTypeReq.getValue());
                quotationTouristType.setName(touristTypeReq.getLabel());
                quotationTouristType.setPeopleNum(touristTypeReq.getPeopleNum());
                quotationTouristType.setAgeBegin(touristTypeReq.getAgeBegin());
                quotationTouristType.setAgeEnd(touristTypeReq.getAgeEnd());
                quotationTouristType.setCreateId(userId);
                quotationTouristTypeMapper.insert(quotationTouristType);
            });
            // 获取天数行程数组
            List<TripQuoteReq> tripQuoteReqs = quotationReq.getTripQuoteReqs();
            for (int i = 0; i < tripQuoteReqs.size(); i++) {
                // 遍历新增行程天数
                CustomizedQuotationTripQuote quotationTripQuote = new CustomizedQuotationTripQuote();
                Long tripQuoteId = SnowflakeIdWorker.nextId();
                quotationTripQuote.setId(tripQuoteId);
                quotationTripQuote.setQuotationId(quotationId);
                quotationTripQuote.setTotalPeople(0);
                quotationTripQuote.setTotalAmount(tripQuoteReqs.get(i).getTotalAmount());
                quotationTripQuote.setDay(i);
                quotationTripQuote.setCurrencyId(tripQuoteReqs.get(i).getCurrency().getValue());
                quotationTripQuote.setCurrency(tripQuoteReqs.get(i).getCurrency().getText());
                quotationTripQuote.setExchangeRate(tripQuoteReqs.get(i).getCurrency().getMarketExchangeRate());
                quotationTripQuote.setCreateId(userId);
                quotationTripQuoteMapper.insert(quotationTripQuote);

                // 遍历新增单个行程天数内的服务项目
                List<TripQuoteServiceItemsReq> serviceItems = tripQuoteReqs.get(i).getServiceItems();
                Optional.ofNullable(serviceItems).orElse(new ArrayList<>()).forEach(tripQuoteServiceItemsReq -> {
                    CustomizedQuotationTripQuoteServiceItems quoteServiceItems = new CustomizedQuotationTripQuoteServiceItems();
                    quoteServiceItems.setId(SnowflakeIdWorker.nextId());
                    quoteServiceItems.setQuotationId(quotationId);
                    quoteServiceItems.setDateId(tripQuoteId);
                    quoteServiceItems.setMainDataId(tripQuoteServiceItemsReq.getServiceType().getValue());
                    quoteServiceItems.setServiceTypeName(tripQuoteServiceItemsReq.getServiceType().getLabel());
                    quoteServiceItems.setName(tripQuoteServiceItemsReq.getProjectName());
                    quoteServiceItems.setServiceInstruction(tripQuoteServiceItemsReq.getServiceInstruction());
                    quoteServiceItems.setSinglePrice(tripQuoteServiceItemsReq.getSinglePrice());
                    quoteServiceItems.setTotalNum(tripQuoteServiceItemsReq.getAmount());
                    quoteServiceItems.setTotalPrice(tripQuoteServiceItemsReq.getTotalPrice());
                    quoteServiceItems.setCreateId(userId);
                    quotationTripQuoteServiceItemsMapper.insert(quoteServiceItems);
                });
            }
        }

        /**
         * 代收费用
         */
        // 根据报价号删除费用表记录和服务项目表记录
        CustomizedQuotationCollectionFee collectionFee = new CustomizedQuotationCollectionFee();
        QueryWrapper<CustomizedQuotationCollectionFee> collectionFeeWrapper = new QueryWrapper<>();
        collectionFeeWrapper.eq("quotation_id",quotationId);
        collectionFee.setIsDeleted(1);
        collectionFee.setModifiedId(userId);
        quotationCollectionFeeMapper.update(collectionFee,collectionFeeWrapper);

        QueryWrapper<CustomizedQuotationCollectionTouristFee> touristFeeWrapper = new QueryWrapper<>();
        touristFeeWrapper.eq("quotation_id",quotationId);
        List<CustomizedQuotationCollectionTouristFee> touristFeeList = quotationCollectionTouristFeeMapper.selectList(touristFeeWrapper);
        if(CollectionUtils.isNotEmpty(touristFeeList)){
            List<Long> touristFeeIds = touristFeeList.stream().map(CustomizedQuotationCollectionTouristFee::getId).distinct().collect(Collectors.toList());
            quotationCollectionTouristFeeMapper.deleteBatchIds(touristFeeIds);
        }
        List<CollectionFeeReq> collectionFees = quotationReq.getCollectionFees();
        Optional.ofNullable(collectionFees).orElse(new ArrayList<>()).forEach(collectionFeeReq -> {
            // 遍历新增代收费用
            CustomizedQuotationCollectionFee quotationCollectionFee = new CustomizedQuotationCollectionFee();
            Long collectionId = SnowflakeIdWorker.nextId();
            quotationCollectionFee.setId(collectionId);
            quotationCollectionFee.setQuotationId(quotationId);
            // TODO 代收费用类型临时注释
            if (collectionFeeReq.getProject() != null){
                quotationCollectionFee.setMainDataId(collectionFeeReq.getProject().getValue());
                quotationCollectionFee.setProjectName(collectionFeeReq.getProject().getLabel());
            }
            quotationCollectionFee.setCurrencyId(collectionFeeReq.getCurrency().getValue());
            quotationCollectionFee.setCurrency(collectionFeeReq.getCurrency().getText());
            quotationCollectionFee.setExchangeRate(collectionFeeReq.getCurrency().getMarketExchangeRate());
            quotationCollectionFee.setRemark(collectionFeeReq.getRemark());
            quotationCollectionFee.setCreateId(userId);
            quotationCollectionFeeMapper.insert(quotationCollectionFee);
            // 代收费用服务项目
            List<CollectionTouristFeeReq> touristFees = collectionFeeReq.getTouristFees();
            Optional.ofNullable(touristFees).orElse(new ArrayList<>()).forEach(collectionTouristFeeReq -> {
                CustomizedQuotationCollectionTouristFee quotationCollectionTouristFee = new CustomizedQuotationCollectionTouristFee();
                quotationCollectionTouristFee.setId(SnowflakeIdWorker.nextId());
                quotationCollectionTouristFee.setQuotationId(quotationId);
                quotationCollectionTouristFee.setCollectionId(collectionId);
                quotationCollectionTouristFee.setTouristTypeId(collectionTouristFeeReq.getTouristTypeId());
                quotationCollectionTouristFee.setTouristTypeName(collectionTouristFeeReq.getTouristTypeName());
                quotationCollectionTouristFee.setTotalAmount(collectionTouristFeeReq.getAmount());
                quotationCollectionTouristFee.setCurrencyId(collectionTouristFeeReq.getCurrencyId());
                quotationCollectionTouristFee.setCurrency(collectionTouristFeeReq.getCurrencyName());
                quotationCollectionTouristFee.setExchangeRate(collectionTouristFeeReq.getExchangeRate());
                quotationCollectionTouristFeeMapper.insert(quotationCollectionTouristFee);
            });
        });
        return null == quotationId ? 0L: quotationId;
    }

    /**
     * 报价单列表
     *
     * @param quotationListReq
     * @param currentUser
     * @return
     */
    @Override
    public PageResponse<QuotationListDTO> list(QuotationListReq quotationListReq, TokenUser currentUser) {
        if (quotationListReq.getDepartType() == null){
            quotationListReq.setDepartType(3);
        }
        Result<List<Long>> permissionResult = sysPermissionService.queryPermission(quotationListReq.getMenuId(), currentUser.getId());
        if (!permissionResult.isSuccess()) {
            SystemError result = SystemError.getDefined(permissionResult.getCode());
            throw new BusinessException(result);
        }
        //分页条件查询
        QueryWrapper<CustomizedQuotation> quotationWrapper = new QueryWrapper<>();
        quotationWrapper.like(StringUtils.isNotBlank(quotationListReq.getQuotationNumber()),"quotation_number",quotationListReq.getQuotationNumber());
        quotationWrapper.or();
        quotationWrapper.like(StringUtils.isNotBlank(quotationListReq.getQuotationNumber()),"quotation_title",quotationListReq.getQuotationNumber());
        quotationWrapper.eq(quotationListReq.getBigClientId() != null,"big_client_id",quotationListReq.getBigClientId());
        quotationWrapper.eq(quotationListReq.getOpId() != null,"create_id",quotationListReq.getOpId());
        quotationWrapper.eq(quotationListReq.getQuotationStatus() != null && quotationListReq.getQuotationStatus() != 0,"quotation_status",quotationListReq.getQuotationStatus());
        quotationWrapper.eq(quotationListReq.getQuotationType() != null && quotationListReq.getQuotationType() != 0,"quotation_type",quotationListReq.getQuotationType());
        quotationWrapper.eq("depart_type",quotationListReq.getDepartType());
        quotationWrapper.lambda().in(!GlobalConstants.Role.isAdmin(currentUser.getUsername()), CustomizedQuotation::getCreateId, permissionResult.getData());
        if (quotationListReq.getBeginDate() != null && quotationListReq.getEndDate() != null){
            quotationListReq.setEndDate(quotationListReq.getEndDate().plusDays(1L));
            quotationWrapper.between("gmt_create",quotationListReq.getBeginDate(),quotationListReq.getEndDate());
        }
        quotationWrapper.orderByDesc("gmt_create");
        Page<CustomizedQuotation> iPage = new Page<>(quotationListReq.getPageNo(), quotationListReq.getPageSize());
        IPage<CustomizedQuotation> quotationIPage = quotationMapper.selectPage(iPage, quotationWrapper);
        if (CollectionUtils.isEmpty(quotationIPage.getRecords())) {
            return PageResponse.empty(quotationIPage.getCurrent());
        }
        List<QuotationListDTO> quotationListDTOList = new ArrayList<>();
        quotationIPage.getRecords().forEach(quotation -> {
            QuotationListDTO quotationListDTO = EntityUtil.copy(quotation,QuotationListDTO.class);
            quotationListDTO.setGmtCreate(quotation.getGmtCreate().toLocalDate());
            //查询部门
            if (quotation.getCreateId() != null){
                UserDTO opUser = sysUserService.queryCacheUser(quotation.getCreateId());
                if (opUser != null){
                    quotationListDTO.setOpName(opUser.getFullName());
                    quotationListDTO.setOpDepart(opUser.getDept());
                }
            }
            CustomizedInquiry inquiry = customizedInquiryMapper.selectById(quotation.getInquiryId());
            if (inquiry != null){
                if (inquiry.getSalespersonId() != null){
                    UserDTO salesUser = sysUserService.queryCacheUser(inquiry.getSalespersonId());
                    if (salesUser != null){
                        quotationListDTO.setSalesPersonName(salesUser.getFullName());
                        quotationListDTO.setSalesPersonDepart(salesUser.getDept());
                    }
                }
                if (Objects.equals(quotation.getQuotationStatus(),1)){
                    //继续询价
                    quotationListDTO.setFeedbackInfo(inquiry.getFeedbackInfo());
                }
            }
            quotationListDTOList.add(quotationListDTO);
        });
        PageResponse<QuotationListDTO> result = new PageResponse<>(quotationListDTOList, quotationIPage.getCurrent() == 1, quotationIPage.getTotal() <= (quotationIPage.getCurrent() * quotationIPage.getSize()), quotationIPage.getTotal(), quotationIPage.getCurrent(), quotationIPage.getSize());
        return result;
    }

    /**
     * 报价单详情
     *
     * @param quotationInfoReq
     * @return
     */
    @Override
    public Result query(QuotationInfoReq quotationInfoReq) {
        //报价详情
        CustomizedQuotation quotation = getQuotationBaseInfo(quotationInfoReq.getQuotationNumber());
        if (quotation == null){
            throw new BusinessException(SystemError.CUSTOM_3005);
        }
        QuotationInfoDTO quotationInfoDTO = EntityUtil.copy(quotation, QuotationInfoDTO.class);
        if (StringUtils.isNotBlank(quotation.getContactTelephones())){
            try {
                quotationInfoDTO.setContactTelephoneJsonList(JSON.parseArray(quotation.getContactTelephones(), ContactTelephoneJson.class));
            }catch (Exception e){
                quotationInfoDTO.setContactTelephones(quotation.getContactTelephones());
            }
        }
        quotationInfoDTO.setContactCnFullName(StrUtil.concat(true, quotation.getContactCnSurname(), quotation.getContactCnName()));
        quotationInfoDTO.setContactEnFullName(StrUtil.concat(true,quotation.getContactEnSurname(),quotation.getContactEnName()));
        //总价
        BigDecimal totalAmount = BigDecimal.ZERO;
        //套餐
        if (quotation.getQuotationType().intValue() == NumberConstant.ONE.getValue()){
            //自由报价
            List<FreePackageDTO> freePackageDTOList = getFreePackageList(quotation.getId(),totalAmount);
            quotationInfoDTO.setFreePackageList(freePackageDTOList);
        }else{
            //行程报价
            List<TripQuoteDTO> tripQuoteDTOList = getTripQuoteList(quotation.getId(),totalAmount);
            quotationInfoDTO.setTripQuoteList(tripQuoteDTOList);
        }
        //代收费用
        List<CollectionFeeDTO> collectionFeeDTOList = getCollectionFeelist(quotation.getId(),totalAmount);
        if (CollectionUtils.isNotEmpty(collectionFeeDTOList)){
            //小计
            List<SubtotalDTO> subtotalList = quotationCollectionTouristFeeMapper.sumAmountByTouristType(quotation.getId());
            quotationInfoDTO.setSubtotalList(subtotalList);
        }
        quotationInfoDTO.setCollectionFeeList(collectionFeeDTOList);
        quotationInfoDTO.setTotalAmount(totalAmount);
        return Result.success(quotationInfoDTO);
    }

    /**
     * 报价单编辑页面详情
     *
     * @param quotationInfoReq
     * @return
     */
    @Override
    public Result<QuotationEditInfoDTO> quotationEditInfo(QuotationInfoReq quotationInfoReq) {
        //报价详情
        CustomizedQuotation quotation = getQuotationBaseInfo(quotationInfoReq.getQuotationNumber());
        if (quotation == null){
            throw new BusinessException(SystemError.CUSTOM_3005);
        }
        //套餐总费用
        BigDecimal totalAmount = BigDecimal.ZERO;
        //总人数
        Integer peopleNum = 0;
        //总代收费用
        BigDecimal totalCollectionFee = BigDecimal.ZERO;
        QuotationEditInfoDTO editInfoDTO = EntityUtil.copy(quotation, QuotationEditInfoDTO.class);
        //客户类型
        CustomerTypeReq customerTypeReq = new CustomerTypeReq();
        customerTypeReq.setCustomerType(quotation.getCustomerType());
        customerTypeReq.setBigClientId(quotation.getBigClientId());
        customerTypeReq.setBigClientName(quotation.getBigClientName());
        editInfoDTO.setCustomerTypeReq(customerTypeReq);
        //联络人
        ContactReq contactReq = new ContactReq();
        contactReq.setContactCnSurname(quotation.getContactCnSurname());
        contactReq.setContactCnName(quotation.getContactCnName());
        contactReq.setContactEnSurname(quotation.getContactEnSurname());
        contactReq.setContactEnName(quotation.getContactEnName());
        editInfoDTO.setContactReq(contactReq);
        //代收费用
        List<CollectionFeeReq> collectionFees = getQuotationEditCollectionFeeList(quotation.getId(), totalCollectionFee);
        editInfoDTO.setCollectionFees(collectionFees);
        if (quotation.getQuotationType().intValue() == NumberConstant.ONE.getValue()){
            //自由报价套餐数组
            List<FreeQuoteReqPackageReq> reqPackages = getQuotationEditFreePackageList(quotation.getId(),totalAmount);
            editInfoDTO.setReqPackages(reqPackages);
        }else{
            //行程报价套餐数组
            List<TripQuoteReq> tripQuoteReqs = getQuotationEditTripQuoteList(quotation.getId(), totalAmount, peopleNum);
            editInfoDTO.setTripQuoteReqs(tripQuoteReqs);
        }
        //旅客人数数组-行程报价套餐里面的旅客
        List<QuotationTouristTypeReq> touristTypes = getQuotationEditQuotationTouristTypeList(quotation.getId(),1,null);
        editInfoDTO.setTouristTypes(touristTypes);
        return Result.success(editInfoDTO);
    }

    /**
     * 旅客人数数组-行程报价套餐里面的旅客
     * @param quotationId
     * @param type (1 行程报价,2 自由报价)
     * @param packageId 自由报价套餐id
     * @return
     */
    public List<QuotationTouristTypeReq> getQuotationEditQuotationTouristTypeList(Long quotationId,int type,Long packageId) {
        List<QuotationTouristTypeReq> touristTypes = new ArrayList<>();
        QueryWrapper<CustomizedQuotationTouristType> touristTypeWrapper = new QueryWrapper<>();
        touristTypeWrapper.eq("quotation_id",quotationId);
        if (type == NumberConstant.ONE.getValue()){
            //行程报价
            touristTypeWrapper.isNull("package_id");
        }else{
            //自由报价
            touristTypeWrapper.eq("package_id",packageId);
        }
        touristTypeWrapper.eq("is_deleted",0);
        touristTypeWrapper.orderByAsc("sort");
        List<CustomizedQuotationTouristType> touristTypeList = quotationTouristTypeMapper.selectList(touristTypeWrapper);
        if (touristTypeList != null && touristTypeList.size() > 0){
            touristTypeList.forEach(touristType -> {
                QuotationTouristTypeReq touristTypeReq = EntityUtil.copy(touristType, QuotationTouristTypeReq.class);
                touristTypeReq.setLabel(touristType.getName());
                touristTypeReq.setValue(touristType.getMainDataId());
                touristTypes.add(touristTypeReq);
            });
        }
        return touristTypes;
    }

    /**
     * 获取报价编辑页面行程报价套餐列表
     * @param quotationId
     * @param totalAmount
     * @param peopleNum
     * @return
     */
    public List<TripQuoteReq> getQuotationEditTripQuoteList(Long quotationId, BigDecimal totalAmount, Integer peopleNum) {
        List<TripQuoteReq> tripQuoteReqs = new ArrayList<>();
        QueryWrapper<CustomizedQuotationTripQuote> tripQuoteWrapper = new QueryWrapper<>();
        tripQuoteWrapper.eq("quotation_id",quotationId);
        tripQuoteWrapper.eq("is_deleted",0);
        tripQuoteWrapper.orderByAsc("day");
        //行程报价套餐列表
        List<CustomizedQuotationTripQuote> tripQuoteList = quotationTripQuoteMapper.selectList(tripQuoteWrapper);
        if (tripQuoteList != null && tripQuoteList.size() > 0){
            for (CustomizedQuotationTripQuote tripQuote : tripQuoteList){
                if (tripQuote.getTotalAmount() != null){
                    totalAmount = totalAmount.add(tripQuote.getTotalAmount());
                }
                if (tripQuote.getTotalPeople() != null){
                    peopleNum = peopleNum + tripQuote.getTotalPeople();
                }
                TripQuoteReq tripQuoteReq = EntityUtil.copy(tripQuote, TripQuoteReq.class);
                Currency currency = new Currency();
                currency.setValue(tripQuote.getCurrencyId());
                currency.setText(tripQuote.getCurrency());
                currency.setMarketExchangeRate(tripQuote.getExchangeRate());
                tripQuoteReq.setCurrency(currency);
                //行程报价服务项目数组
                QueryWrapper<CustomizedQuotationTripQuoteServiceItems> serviceItemsWrapper = new QueryWrapper<>();
                serviceItemsWrapper.eq("date_id",tripQuote.getId());
                serviceItemsWrapper.eq("is_deleted",0);
                List<CustomizedQuotationTripQuoteServiceItems> serviceItemsList = quotationTripQuoteServiceItemsMapper.selectList(serviceItemsWrapper);
                if (serviceItemsList != null && serviceItemsList.size() > 0){
                    List<TripQuoteServiceItemsReq> serviceItems = new ArrayList<>();
                    serviceItemsList.forEach(serviceItem -> {
                        TripQuoteServiceItemsReq itemsReq = EntityUtil.copy(serviceItem,TripQuoteServiceItemsReq.class);
                        MainData serviceType = new MainData();
                        serviceType.setLabel(serviceItem.getServiceTypeName());
                        serviceType.setValue(serviceItem.getMainDataId());
                        itemsReq.setServiceType(serviceType);
                        itemsReq.setProjectName(serviceItem.getName());
                        itemsReq.setAmount(serviceItem.getTotalNum());
                        serviceItems.add(itemsReq);
                    });
                    tripQuoteReq.setServiceItems(serviceItems);
                }
                tripQuoteReqs.add(tripQuoteReq);
            }
        }
        return tripQuoteReqs;
    }

    /**
     * 获取报价编辑页面自由报价套餐列表
     * @param quotationId
     * @param totalAmount
     * @return
     */
    public List<FreeQuoteReqPackageReq> getQuotationEditFreePackageList(Long quotationId,BigDecimal totalAmount) {
        List<FreeQuoteReqPackageReq> reqPackages = new ArrayList<>();
        QueryWrapper<CustomizedQuotationFreeQuotePackage> freePackageWrapper = new QueryWrapper<>();
        freePackageWrapper.eq("quotation_id",quotationId);
        freePackageWrapper.eq("is_deleted",0);
        //自由报价套餐列表
        List<CustomizedQuotationFreeQuotePackage> freePackageList = freeQuotePackageMapper.selectList(freePackageWrapper);
        if (freePackageList != null && freePackageList.size() > 0){
            //套餐
            for (CustomizedQuotationFreeQuotePackage freePackage : freePackageList){
                //套餐总费用
                if (freePackage.getTotalAmount() != null){
                    totalAmount = totalAmount.add(freePackage.getTotalAmount());
                }
                FreeQuoteReqPackageReq reqPackage = EntityUtil.copy(freePackage, FreeQuoteReqPackageReq.class);
                Currency currency = new Currency();
                currency.setValue(freePackage.getCurrencyId());
                currency.setText(freePackage.getCurrency());
                currency.setMarketExchangeRate(freePackage.getExchangeRate());
                reqPackage.setCurrency(currency);
                reqPackage.setPackageName(freePackage.getName());
                //旅客类型
                List<QuotationTouristTypeReq> packageTouristTypes = getQuotationEditQuotationTouristTypeList(quotationId, NumberConstant.TWO.getValue(), freePackage.getId());
                reqPackage.setPackageTouristTypes(packageTouristTypes);
                //服务项目
                QueryWrapper<CustomizedQuotationFreeQuoteServiceItems> serviceItemsWrapper = new QueryWrapper<>();
                serviceItemsWrapper.eq("package_id",freePackage.getId());
                serviceItemsWrapper.eq("is_deleted",0);
                List<CustomizedQuotationFreeQuoteServiceItems> freeQuoteServiceItemsList = freeQuoteServiceItemsMapper.selectList(serviceItemsWrapper);
                if (freeQuoteServiceItemsList != null && freeQuoteServiceItemsList.size() > 0){
                    List<FreeQuoteServiceItemsReq> serviceItemsReqs = new ArrayList<>();
                    freeQuoteServiceItemsList.forEach(serviceItem -> {
                        FreeQuoteServiceItemsReq serviceItemsReq = EntityUtil.copy(serviceItem, FreeQuoteServiceItemsReq.class);
                        MainData serviceType = new MainData();
                        serviceType.setValue(serviceItem.getMainDataId());
                        serviceType.setLabel(serviceItem.getServiceTypeName());
                        serviceItemsReq.setServiceType(serviceType);
                        serviceItemsReq.setProjectName(serviceItem.getName());
                        if (serviceItem.getGroupFeeType().intValue() == NumberConstant.ONE.getValue()){
                            //按人均
                            List<TouristPriceDTO> touristPriceDTOList = quotationTouristPriceMapper.queryListByServiceItem(serviceItem.getId(),serviceItem.getQuotationId());
                            if (touristPriceDTOList != null && touristPriceDTOList.size() > 0){
                                List<TouristPriceReq> touristPriceReqs = new ArrayList<>();
                                touristPriceDTOList.forEach(touristPriceDTO -> {
                                    TouristPriceReq touristPriceReq = EntityUtil.copy(touristPriceDTO, TouristPriceReq.class);
                                    touristPriceReq.setPrice(touristPriceDTO.getTotalPrice());
                                    touristPriceReqs.add(touristPriceReq);
                                });
                                serviceItemsReq.setTouristPriceReqs(touristPriceReqs);
                            }
                        }
                        serviceItemsReqs.add(serviceItemsReq);
                    });
                    reqPackage.setServiceItemsReqs(serviceItemsReqs);
                }
                reqPackages.add(reqPackage);
            }
        }
        return reqPackages;
    }

    /**
     * 获取报价编辑页面代收费用列表
     * @param quotationId
     * @param totalCollectionFee
     * @return
     */
    public List<CollectionFeeReq> getQuotationEditCollectionFeeList(Long quotationId, BigDecimal totalCollectionFee) {
        List<CollectionFeeReq> collectionFees = new ArrayList<>();
        QueryWrapper<CustomizedQuotationCollectionFee> collectionFeeWrapper = new QueryWrapper<>();
        collectionFeeWrapper.eq("quotation_id",quotationId);
        collectionFeeWrapper.eq("is_deleted",0);
        collectionFeeWrapper.orderByAsc("gmt_create");
        List<CustomizedQuotationCollectionFee> collectionFeeList = quotationCollectionFeeMapper.selectList(collectionFeeWrapper);
        if (collectionFeeList != null && collectionFeeList.size() > 0){
            for (CustomizedQuotationCollectionFee collectionFee : collectionFeeList){
                CollectionFeeReq collectionFeeReq = new CollectionFeeReq();
                collectionFeeReq.setId(collectionFee.getId());
                Currency currency = new Currency();
                currency.setValue(collectionFee.getCurrencyId());
                currency.setText(collectionFee.getCurrency());
                currency.setMarketExchangeRate(collectionFee.getExchangeRate());
                collectionFeeReq.setCurrency(currency);
                MainData project = new MainData();
                project.setLabel(collectionFee.getProjectName());
                project.setValue(collectionFee.getMainDataId());
                collectionFeeReq.setProject(project);
                collectionFeeReq.setRemark(collectionFee.getRemark());
                //代收费用旅客类型价格数组
                List<CollectionTouristFeeDTO> touristFeeDTOList = quotationCollectionTouristFeeMapper.queryCollectionTouristFeeDetailList(collectionFee.getId(),quotationId);
                if (touristFeeDTOList != null && touristFeeDTOList.size() > 0){
                    List<CollectionTouristFeeReq> touristFees = new ArrayList<>();
                    for (CollectionTouristFeeDTO touristFeeDTO : touristFeeDTOList){
                        if (touristFeeDTO.getTotalAmount() != null){
                            totalCollectionFee = totalCollectionFee.add(touristFeeDTO.getTotalAmount());
                        }
                        CollectionTouristFeeReq touristFeeReq = new CollectionTouristFeeReq();
                        touristFeeReq.setTouristTypeId(touristFeeDTO.getTouristTypeId());
                        touristFeeReq.setTouristTypeName(touristFeeDTO.getTouristTypeName());
                        touristFeeReq.setAmount(touristFeeDTO.getPrice());
                        touristFeeReq.setCurrencyId(touristFeeDTO.getCurrencyId());
                        touristFeeReq.setCurrencyName(touristFeeDTO.getCurrency());
                        touristFeeReq.setExchangeRate(touristFeeDTO.getExchangeRate());
                        touristFees.add(touristFeeReq);
                    }
                    collectionFeeReq.setTouristFees(touristFees);
                }
                collectionFees.add(collectionFeeReq);
            }
        }
        return collectionFees;
    }


    /**
     * 获取代收费用列表
     * @param quotationId
     * @param totalAmount
     * @return
     */
    public List<CollectionFeeDTO> getCollectionFeelist(Long quotationId, BigDecimal totalAmount) {
        List<CollectionFeeDTO> collectionFeeDTOList = new ArrayList<>();
        QueryWrapper<CustomizedQuotationCollectionFee> collectionFeeWrapper = new QueryWrapper<>();
        collectionFeeWrapper.eq("quotation_id",quotationId);
        collectionFeeWrapper.eq("is_deleted",0);
        collectionFeeWrapper.orderByAsc("gmt_create");
        List<CustomizedQuotationCollectionFee> collectionFeeList = quotationCollectionFeeMapper.selectList(collectionFeeWrapper);
        if (collectionFeeList != null && collectionFeeList.size() > 0){
            for (CustomizedQuotationCollectionFee collectionFee : collectionFeeList){
                CollectionFeeDTO collectionFeeDTO = EntityUtil.copy(collectionFee, CollectionFeeDTO.class);
                Currency currency = new Currency();
                currency.setValue(collectionFee.getCurrencyId());
                currency.setText(collectionFee.getCurrency());
                currency.setMarketExchangeRate(collectionFee.getExchangeRate());
                collectionFeeDTO.setCurrency(currency);
                //费用明细
                List<CollectionTouristFeeDTO> touristFeeDTOList = quotationCollectionTouristFeeMapper.queryCollectionTouristFeeDetailList(collectionFee.getId(),quotationId);
                if (touristFeeDTOList != null && touristFeeDTOList.size() > 0){
                    for (CollectionTouristFeeDTO touristFeeDTO : touristFeeDTOList){
                        if (touristFeeDTO.getTotalAmount() != null){
                            totalAmount = totalAmount.add(touristFeeDTO.getTotalAmount());
                        }
                    }
                }
                collectionFeeDTO.setCollectionTouristFeeList(touristFeeDTOList);
                collectionFeeDTOList.add(collectionFeeDTO);
            }
        }
        return collectionFeeDTOList;
    }

    /**
     * 获取行程报价套餐列表
     * @param quotationId
     * @param totalAmount
     * @return
     */
    public List<TripQuoteDTO> getTripQuoteList(Long quotationId, BigDecimal totalAmount) {
        List<TripQuoteDTO> tripQuoteDTOList = new ArrayList<>();
        QueryWrapper<CustomizedQuotationTripQuote> tripQuoteWrapper = new QueryWrapper<>();
        tripQuoteWrapper.eq("quotation_id",quotationId);
        tripQuoteWrapper.eq("is_deleted",0);
        tripQuoteWrapper.orderByAsc("day");
        List<CustomizedQuotationTripQuote> tripQuoteList = quotationTripQuoteMapper.selectList(tripQuoteWrapper);
        if (tripQuoteList != null && tripQuoteList.size() > 0){
            for (CustomizedQuotationTripQuote tripQuote : tripQuoteList){
                if (tripQuote.getTotalAmount() != null){
                    totalAmount = totalAmount.add(tripQuote.getTotalAmount());
                }
                TripQuoteDTO tripQuoteDTO = EntityUtil.copy(tripQuote, TripQuoteDTO.class);
                Currency currency = new Currency();
                currency.setValue(tripQuote.getCurrencyId());
                currency.setText(tripQuote.getCurrency());
                currency.setMarketExchangeRate(tripQuote.getExchangeRate());
                tripQuoteDTO.setCurrency(currency);
                List<QuoteServiceTypeDTO> quoteServiceTypeDTOList = quotationTripQuoteServiceItemsMapper.queryServiceTypeList(tripQuote.getId());
                if (quoteServiceTypeDTOList != null && quoteServiceTypeDTOList.size() > 0){
                    List<QuoteServiceTypeDTO> quoteServiceTypeList = new ArrayList<>();
                    quoteServiceTypeDTOList.forEach(quoteServiceTypeDTO -> {
                        //服务需求列表
                        QueryWrapper<CustomizedQuotationTripQuoteServiceItems> serviceItemsWrapper = new QueryWrapper<>();
                        serviceItemsWrapper.eq("service_type_name",quoteServiceTypeDTO.getServiceTypeName());
                        serviceItemsWrapper.eq("quotation_id",quotationId);
                        serviceItemsWrapper.eq("is_deleted",0);
                        List<CustomizedQuotationTripQuoteServiceItems> serviceItemsList = quotationTripQuoteServiceItemsMapper.selectList(serviceItemsWrapper);
                        List<TripQuoteServiceItemsDTO> tripQuoteServiceItemsDTOList = new ArrayList<>();
                        serviceItemsList.forEach(serviceItems -> {
                            TripQuoteServiceItemsDTO serviceItemsDTO = EntityUtil.copy(serviceItems, TripQuoteServiceItemsDTO.class);
                            tripQuoteServiceItemsDTOList.add(serviceItemsDTO);
                        });
                        quoteServiceTypeDTO.setTripQuoteServiceItemsList(tripQuoteServiceItemsDTOList);
                        quoteServiceTypeList.add(quoteServiceTypeDTO);
                    });
                    tripQuoteDTO.setQuoteServiceTypeList(quoteServiceTypeList);
                }
                tripQuoteDTOList.add(tripQuoteDTO);
            }
        }
        return tripQuoteDTOList;
    }

    /**
     * 获取自由报价套餐列表(合并项目类型)
     * @param quotationId
     * @param totalAmount
     * @return
     */
    public List<FreePackageDTO> getFreePackageList(Long quotationId, BigDecimal totalAmount) {
        QueryWrapper<CustomizedQuotationFreeQuotePackage> freePackageWrapper = new QueryWrapper<>();
        freePackageWrapper.eq("quotation_id",quotationId);
        freePackageWrapper.eq("is_deleted",0);
        //套餐列表
        List<CustomizedQuotationFreeQuotePackage> freePackageList = freeQuotePackageMapper.selectList(freePackageWrapper);
        List<FreePackageDTO> freePackageDTOList = new ArrayList<>();
        if (freePackageList != null){
            for (CustomizedQuotationFreeQuotePackage freePackage : freePackageList){
                if (freePackage.getTotalAmount() != null){
                    totalAmount = totalAmount.add(freePackage.getTotalAmount());
                }
                FreePackageDTO freePackageDTO = EntityUtil.copy(freePackage, FreePackageDTO.class);
                Currency currency = new Currency();
                currency.setValue(freePackage.getCurrencyId());
                currency.setText(freePackage.getCurrency());
                currency.setMarketExchangeRate(freePackage.getExchangeRate());
                freePackageDTO.setCurrency(currency);
                //查询项目分类
                List<ServiceTypeDTO> serviceTypeDTOList = freeQuoteServiceItemsMapper.queryServiceTypeList(freePackage.getId(),freePackage.getQuotationId());
                List<ServiceTypeDTO> serviceTypeList = new ArrayList<>();
                if (serviceTypeDTOList != null && serviceTypeDTOList.size() > 0){
                    serviceTypeDTOList.forEach(serviceTypeDTO -> {
                        //服务内容
                        QueryWrapper<CustomizedQuotationFreeQuoteServiceItems> serviceItemsWrapper = new QueryWrapper<>();
                        serviceItemsWrapper.eq("service_type_name",serviceTypeDTO.getServiceTypeName());
                        serviceItemsWrapper.eq("quotation_id",freePackage.getQuotationId());
                        serviceItemsWrapper.eq("is_deleted",0);
                        List<CustomizedQuotationFreeQuoteServiceItems> freeQuoteServiceItemsList = freeQuoteServiceItemsMapper.selectList(serviceItemsWrapper);
                        List<FreeQuoteServiceItemsDTO> freeQuoteServiceItemsDTOList = new ArrayList<>();
                        freeQuoteServiceItemsList.forEach(freeQuoteServiceItems -> {
                            FreeQuoteServiceItemsDTO serviceItemsDTO = EntityUtil.copy(freeQuoteServiceItems, FreeQuoteServiceItemsDTO.class);
                            if (freeQuoteServiceItems.getTotalPrice() != null && freePackage.getExchangeRate() != null){
                                BigDecimal totalPriceHK = freeQuoteServiceItems.getTotalPrice().multiply(new BigDecimal(freePackage.getExchangeRate()));
                                serviceItemsDTO.setTotalPriceHK(totalPriceHK);
                            }
                            if (freeQuoteServiceItems.getGroupFeeType().intValue() == NumberConstant.ONE.getValue()){
                                //按人均
                                List<TouristPriceDTO> touristPriceDTOList = quotationTouristPriceMapper.queryListByServiceItem(freeQuoteServiceItems.getId(),freeQuoteServiceItems.getQuotationId());
                                serviceItemsDTO.setTouristPriceList(touristPriceDTOList);
                            }
                            freeQuoteServiceItemsDTOList.add(serviceItemsDTO);
                        });
                        serviceTypeDTO.setFreeQuoteServiceItemsList(freeQuoteServiceItemsDTOList);
                        serviceTypeList.add(serviceTypeDTO);
                    });
                }
                freePackageDTO.setServiceTypeList(serviceTypeList);
                freePackageDTOList.add(freePackageDTO);
            }
        }
        return freePackageDTOList;
    }


    /**
     * 获取报价单基本信息
     * @param quotationNumber
     * @return
     */
    public CustomizedQuotation getQuotationBaseInfo(String quotationNumber) {
        QueryWrapper<CustomizedQuotation> quotationWrapper = new QueryWrapper<>();
        quotationWrapper.like("quotation_number", quotationNumber);
        quotationWrapper.or();
        quotationWrapper.like("quotation_title",quotationNumber);
        CustomizedQuotation quotation = quotationMapper.selectOne(quotationWrapper);
        return quotation;
    }


}
